package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.FabulousVideoBean;
import dhm.com.hpx.entity.FavoriteVideoBean;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.entity.GetVideoBean;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.WXUtil;
import dhm.com.hpx.utils.mapapi.Util;
import dhm.com.hpx.view.FullWindowVideoView;

public class VideoActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.see)
    TextView see;
    @BindView(R.id.zhuan)
    TextView zhuan;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.guanzhu)
    Button guanzhu;
    @BindView(R.id.like)
    ImageView like;
    @BindView(R.id.text_like)
    TextView textLike;
    @BindView(R.id.collectionn)
    ImageView collectionn;
    @BindView(R.id.collections)
    ImageView collections;
    @BindView(R.id.text_colle)
    TextView textColle;
    @BindView(R.id.img_thumb)
    ImageView imgThumb;
    @BindView(R.id.img_play)
    ImageView imgPlay;
    @BindView(R.id.love)
    TextView love;
    @BindView(R.id.video_view)
    FullWindowVideoView videoView;
    private String video_id;


    private PressenterImpl pressenter;
    private String uid;
    private boolean iscollection=false;
    private GetVideoBean getVideoBean;
    private String coverImg;

    private IWXAPI api;
    private static Bitmap bitmaps;


    private String userType;

    @Override
    protected int getLayout() {
        return R.layout.activity_video;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        userType = SpUtils.getString(this, "userType");
        getWindow().setStatusBarColor(getResources().getColor(R.color.mainblack));
        api = WXAPIFactory.createWXAPI(this, Constant.Wx_APP_ID, false);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//            getWindow().getDecorView().setSystemUiVisibility(View.);

            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);

        }
        video_id = getIntent().getStringExtra("video_id");
        uid = SpUtils.getString(this, "uid");

        pressenter = new PressenterImpl();
        pressenter.attachView(this);

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("video_id", video_id);
        map.put("uid", uid);

        pressenter.sendMessage(this, Constant.video_info, map, GetVideoBean.class);

    }

    @Override
    protected void initData() {

    }
    boolean isPlaying = true;

    private boolean isloved=false;
    private boolean iscollet=false;

    boolean iscanclelike=false;

    final MediaPlayer[] mediaPlayer = new MediaPlayer[1];
    @Override
    public void requesta(Object data) {
        if (data instanceof GetVideoBean) {
            getVideoBean = (GetVideoBean) data;
            if (getVideoBean.getCode() == 1) {
                videoView.setVideoURI(Uri.parse(Constant.PATH+ getVideoBean.getData().getVideo_url()));
                videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                    }
                });
                videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        mediaPlayer[0] = mp;
                        mp.setLooping(true);
                        imgThumb.animate().alpha(0).setDuration(200).start();
                        return false;
                    }
                });
                love.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (videoView.isPlaying()) {
                            imgPlay.animate().alpha(0.7f).start();
                            videoView.pause();
                            isPlaying = false;
                        } else {
                            imgPlay.animate().alpha(0f).start();
                            videoView.start();
                            isPlaying = true;
                        }
                    }
                });

                videoView.start();

                content.setText(getVideoBean.getData().getVideo_desc());
                if (getVideoBean.getData().getIs_fabulous()==1){
                    isloved=true;
                    like.setImageResource(R.mipmap.likes);

                }else {
                    like.setImageResource(R.mipmap.liken);
                    isloved=false;
                }


                if (getVideoBean.getData().getIs_favorites()==1){
                    iscollection = true;
                    collections.setVisibility(View.VISIBLE);
                    collectionn.setVisibility(View.GONE);
                }else {
                    iscollection=false;
                    collectionn.setVisibility(View.VISIBLE);
                    collections.setVisibility(View.GONE);
                }
            }


            coverImg = getIntent().getStringExtra("coverImg");

            Map<String, String> map = new HashMap<>();
            map.put("token", Constant.TOKEN);
            map.put("uid", uid);
            pressenter.sendMessage(this, Constant.get_userinfo, map, GetUserInfoBean.class);
        }else if (data instanceof Bean){
            Bean bean= (Bean) data;
            Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            if (bean.getCode()==1){
                if (bean.getMessage().equals("点赞成功")){
                    isloved=true;
                    like.setImageResource(R.mipmap.likes);
                }else if (bean.getMessage().equals("取消成功")){
                    if (iscanclelike){
                        isloved=false;
                        like.setImageResource(R.mipmap.liken);
                    }else {
                        iscollection=false;
                        collectionn.setVisibility(View.VISIBLE);
                        collections.setVisibility(View.GONE);
                    }
                }if (bean.getMessage().equals("收藏成功")){
                    iscollection=true;
                    collections.setVisibility(View.VISIBLE);
                    collectionn.setVisibility(View.GONE);
                }
            }
        }else if (data instanceof FabulousVideoBean){
            FabulousVideoBean fabulousVideoBean= (FabulousVideoBean) data;
            if (fabulousVideoBean.getCode()==1){
                page++;
                for (int i = 0; i < fabulousVideoBean.getData().size(); i++) {
                    if (video_id.equals(fabulousVideoBean.getData().get(i).getVideoId()+"")){
                        Map<String,String> map=new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("uid",uid);
                        map.put("type",2+"");
                        map.put("cid",fabulousVideoBean.getData().get(i).getFabulousId()+"");

                        pressenter.sendMessage(this,Constant.fabulouscancel,map,Bean.class);
                        return;
                    }
                }

                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("page",page+"");
                pressenter.sendMessage(this,Constant.listVideoQuery_fablulous,map, FabulousVideoBean.class);
            }
        }else if (data instanceof FavoriteVideoBean){
            FavoriteVideoBean favoriteVideoBean= (FavoriteVideoBean) data;
            if (favoriteVideoBean.getCode()==1){
                page++;
                for (int i = 0; i < favoriteVideoBean.getData().size(); i++) {
                    if (video_id.equals(favoriteVideoBean.getData().get(i).getVideoId()+"")){
                        Map<String,String> map=new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("uid",uid);
                        map.put("type",2+"");
                        map.put("cid",favoriteVideoBean.getData().get(i).getFavoriteId()+"");

                        pressenter.sendMessage(this,Constant.cancel,map,Bean.class);
                        return;
                    }
                }

                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("page",page+"");
                pressenter.sendMessage(this,Constant.listVideoQuery_fablulous,map, FabulousVideoBean.class);
            }


        }else if (data instanceof GetUserInfoBean){
            GetUserInfoBean getUserInfoBean= (GetUserInfoBean) data;
            if (getUserInfoBean.getCode()==1){
                image.setImageURI(Constant.PATH+getUserInfoBean.getData().getHeadsmall());
                nick.setText(getUserInfoBean.getData().getUser_nickname());
            }


        }
    }

    @Override
    public void fail(String error) {

    }

    int page=1;

    @OnClick({R.id.img_thumb, R.id.img_play, R.id.guanzhu, R.id.like, R.id.back, R.id.sahre, R.id.collections, R.id.collectionn})
    public void onViewClicked(View view) {
        Map<String,String> map;
        switch (view.getId()) {
            case R.id.img_thumb:
                break;
            case R.id.img_play:
                break;
            case R.id.guanzhu:
                break;
            case R.id.like:
                if (isloved){
                    //点赞取消点赞
                    page=1;
                    map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("uid",uid);
                    map.put("page",page+"");
                    pressenter.sendMessage(this,Constant.listVideoQuery_fablulous,map, FabulousVideoBean.class);
                    iscanclelike=true;
                }else {
                    //未点赞点赞
                    map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("uid",uid);
                    map.put("type","2");
                    map.put("id",video_id);
                    pressenter.sendMessage(this,Constant.fabulousadd,map,Bean.class);
                }

                break;
            case R.id.collectionn:
                //未收藏收藏
                map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("type","2");
                map.put("id",video_id);
                pressenter.sendMessage(this,Constant.add,map, Bean.class);
                break;
            case R.id.collections:
                //收藏取消收藏
                iscanclelike=false;
                page=1;
                map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("page",page+"");
                pressenter.sendMessage(this,Constant.listVideoQuery,map, FavoriteVideoBean.class);

                break;
            case R.id.back:
                finish();
                break;
            case R.id.sahre:

                switch (userType) {
                    case "0":
                        Toast.makeText(this, "暂无权限查看，请升级会员" + userType, Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(this, "您的会员已过期" + userType, Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:


                        if (getVideoBean==null||coverImg==null||coverImg.equals("")){
                            Toast.makeText(this, "正在加载，请稍后...", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //初始化一个WXWebpageObject，填写url
                        WXWebpageObject webpage = new WXWebpageObject();
//                webpage.webpageUrl = "http://www.quqike.cn/appapi/appletscode/getwxacode/uid/" + uid + "/type/1/article_id/" + article_id;

                        webpage.webpageUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constant.urlappid+"&redirect_uri=" +
                                Constant.PATH+"appapi/extension/shouquan/uid/" + uid + "/type/2/target_id/"+video_id +
                                "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";



//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                        WXMediaMessage msg = new WXMediaMessage(webpage);
                        msg.title = getVideoBean.getData().getVideo_title();
                        msg.description = getVideoBean.getData().getVideo_desc();

                        if (coverImg==null||coverImg.equals("")){
                            Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.main_yao);
                            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

//构造一个Req
                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.transaction = buildTransaction("webpage");
                            req.message = msg;
                            req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
//调用api接口，发送数据到微信
                            api.sendReq(req);
                        }else {
                            initNetWorkImage(api,VideoActivity.this,Constant.PATH+coverImg,"weChat",msg);
                        }

                        map=new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("target_id",video_id);
                        map.put("uid",uid);
                        map.put("type","1");
                        pressenter.sendMessage(VideoActivity.this,Constant.add_share,map,Bean.class);


                }


                break;
                default:
        }
    }

    @SuppressLint("StaticFieldLeak")
    public static void initNetWorkImage(final IWXAPI wxapi, final Context context, final String imgUrl, final String flag, final WXMediaMessage msg) {
        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... voids) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(context)
                            .asBitmap()
                            .load(imgUrl)
                            .submit(100, 100).get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                bitmaps = bitmap;
                msg.thumbData = WXUtil.bitmap2Bytes(bitmaps, 150);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                if (flag.equals("weChat")) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag.equals("friends")) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                }
                wxapi.sendReq(req);
            }
        }.execute();
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
